import re

from django.http import Http404
from django.shortcuts import render

from myblog.models import Article


def category_index(request, cat):
    try:
        article_list = Article.objects.filter(category=cat).order_by('-pub_date')
    except Exception as e:
        raise Http404
    article_image_list = []
    for article in article_list:
        content = article.content
        # <p>测试文件<img src="/media/uploads/blog/images/123_20180730101259_199.png" alt="123.png"/></p>
        try:
            ret = re.search(r'<img src="(.*?)" alt=".*"/>', content)
            if ret:
                article_image_list.append((article, ret.group(1)))
            else:
                article_image_list.append((article, None))
        except Exception as e:
            raise Http404
    return render(request, 'blog/category_index.html', {'article_image_list': article_image_list})

